#ifndef __APP_MQTT_H__
#define __APP_MQTT_H__

#include "MQTTPacket/MQTTPacket.h"
#include <netinet/tcp.h>
#ifdef WITH_TLS
#include <openssl/ssl.h>
#endif

#define MQTT_TIMEOUT_MS         (10000)
#define RECIVER_MAX_SIZE        (1024*1024)
#define MQTT_TOPIC_LEN          128

enum {
	QOS0 = 0,
	QOS1,
	QOS2
};



typedef struct {
	uint32_t period;
	uint64_t start;
}m_timer;

typedef struct {
	int         qos;
	uint8_t     retained;
	uint8_t     dup;
	uint16_t    pid;
	MQTTString  topic;
	uint8_t     *payload;
	int         payloadlen;
}mqtt_message_t;

typedef struct{
	char hostname[128];
	int  port;
	char portnr[32];
	char clientid[128];
	char model[128];
	char username[128];
	char password[128];
	int  keepalive;
	bool ssl_enable;
	bool cleansession;
}mqtt_param_t;

typedef struct {
	char         name[16];
#ifdef WITH_TLS
	SSL_CTX *ssl_ctx;
	SSL     *ssl;
#endif
	pthread_mutex_t mutex;
	int          socket;
	int8_t       connected; //0表示未连接，1表示连接，-1表示已经断开
	bool         wakeup;
	int8_t       qos;
	uint16_t     pid;
	int          keep_ms;
	int          sendbuf_size;
	int          readbuf_size;
	uint8_t      *readbuf;
	char         not_clean;
	char         pingreq;
	char         subscribed;
	m_timer      send_timer;
	m_timer      recive_timer;
	void         (*on_message) (mqtt_message_t *, void *);
	void         *msg_arg;
	char         reason[16];
}mqtt_context_t;


int hmqtt_connect(mqtt_context_t *context, mqtt_param_t *param);
int hmqtt_subscribe(mqtt_context_t *context, const char *topic, int qos);
int hmqtt_publish(mqtt_context_t *context, mqtt_message_t *message);
int hmqtt_publish_qos0(mqtt_context_t *context, const char *topic, void *payload, int payloadlen);
int hmqtt_disconnect(mqtt_context_t *context, const char *reason);
int hmqtt_loop(mqtt_context_t *context, uint32_t timeout);
int hmqtt_init(mqtt_context_t *context, void (*on_message)(mqtt_message_t *, void *), void *arg);
int hmqtt_uninit(mqtt_context_t *context);


#endif
